package com.atjinggu.jinggumail.product.exception;

import com.atjinggu.jinggumail.common.enums.BizCodeEnum;
import com.atjinggu.jinggumail.common.utils.R;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;

/**
 * @author jingming
 * @Type JinggumailExceptionControllerAdvice.java
 * @Desc
 * @date 2020/12/19 14:50
 */
@Slf4j
@RestControllerAdvice(basePackages = "com.atjinggu.jinggumail.product.controller")
public class JinggumailExceptionControllerAdvice {

    /**
     * 处理参数校验异常
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R MethodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e){
        HashMap<Object, Object> map = Maps.newHashMap();
        e.getBindingResult().getFieldErrors().stream().forEach(item -> {
            String field = item.getField();
            String message = item.getDefaultMessage();
            map.put(field,message);
        });
        return R.error(BizCodeEnum.VALID_EXCEPTION.getCode(),BizCodeEnum.VALID_EXCEPTION.getMessage()).put("data",map);
    }


    @ExceptionHandler(Throwable.class)
    public R handler(Throwable e){
        log.error(e.getMessage());
        return R.error(BizCodeEnum.UNKNOWN_EXCEPTION.getCode(),BizCodeEnum.UNKNOWN_EXCEPTION.getMessage());
    }
}